﻿using LIB;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    
    public List<LIB.easyDoc> listDoc = new List<LIB.easyDoc>();
    protected void Page_Load(object sender, EventArgs e)
    {
        //string test = "a.aspx.cs";
        //string result = LIB.trans.getExt(test);
        //Response.Write(result);
        //Response.End();

        if (!IsPostBack)
        {
            ///加载模板文件夹
            string dir = iData.IO.GetCurrentPath() + "\\..\\templates";
            var dirs = new System.IO.DirectoryInfo(dir);
            var subDirs = dirs.GetDirectories();
            rdTemplateFolders.DataSource = subDirs;
            rdTemplateFolders.DataBind();
        }
    }
    /// <summary>
    /// 绑定模板文件夹里的文件
    /// </summary>
    private void bindTemplateFiles()
    {
        string dir = iData.IO.GetCurrentPath() + "\\..\\templates";
        string currentFile = rdTemplateFolders.SelectedValue;
        if (currentFile == "") currentFile = "default";
        var dirs2 = new System.IO.DirectoryInfo(dir + "\\" + currentFile);
        var files = dirs2.GetFiles();
   
        ckTemplates.DataSource = files;
        ckTemplates.DataBind();
        foreach (ListItem item in ckTemplates.Items)
        {
            item.Selected = true;
        }
    }
    public class Item
    {
        public string Text { get; set; }
        public bool Selected { get; set; }
    }
    /// <summary>
    /// 生成sql语句点击事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnGenCode_Click(object sender, EventArgs e)
    {
        BatDealDocModels();

        lblResult.Text = "";
        var sb = new StringBuilder();
        var sa = new StringBuilder();
        var navTemplateHtml = txtNavTemplate.Text;
        for (int i = 0; i < listDoc.Count; i++)
        {
            var mod = listDoc[i];
            string ret = genSqlCode(mod);
            sb.Append(ret);

            sa.Append(navTemplateHtml.Replace("[[tblName]]", mod.tblName).Replace("[[tblTitle]]", mod.tblTitle));
        }
        lblResult.Text += LIB.trans.codeInTextarea(sb.ToString(), "sql脚本", "所有表");
        lblResult.Text += LIB.trans.codeInTextarea(sa.ToString(), "导航代码", "所有表");
    }

    /// <summary>
    /// 批量处理输入文本到modellist
    /// </summary>
    private void BatDealDocModels()
    {
        bool formatAllOk = true;
        string sCont = txtCont.Text;//.Replace("\n", "").Replace("，", ",").Trim();
        var sb = new StringBuilder();
        string[] arrCont = System.Text.RegularExpressions.Regex.Split(sCont, @"-----*", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        for (int i = 0; i < arrCont.Length; i++)
        {
            string cont = arrCont[i];
            var mod = getDocModel(cont);
            listDoc.Add(mod);
            if (mod.docOk)
            {
                sb.AppendFormat("<p>第{0}表{1}正常</p>,{2}", i + 1, mod.tblName, mod.v_table);
            }
            else
            {
                sb.AppendFormat("<p>第{0}表异常:<br>,{1}</p>{2}", i + 1, mod.docMsg,mod.v_table);
                formatAllOk = false;
            }
        }
        lblMsg.Text = "";
        if (!formatAllOk)
        {
            lblMsg.Text = sb.ToString();
            return;
        }
    }

    /// <summary>
    /// 单个处理输入文本到model
    /// </summary>
    /// <param name="sCont"></param>
    /// <returns></returns>
    private LIB.easyDoc getDocModel(string sCont)
    {
        sCont=sCont.Replace("\n", "\r").Replace("\r\r", "\r").Replace("，", ",").Trim();

        LIB.easyDoc mDoc = new LIB.easyDoc();
        string[] arr_rows = sCont.Split('\r');
        int rowCount = arr_rows.Length;
        if (rowCount < 3)
        {
            mDoc.docMsg= "行数不足";
            return mDoc;
        }

        //第一行 表名解析
        string row = arr_rows[0];
        string[] arr_items = row.Split(',');
        if (arr_items.Length < 2)
        {
            mDoc.docMsg = "首行非法，没有标名。";
            return mDoc;
        }
        mDoc.dbName = txtDbName.Text.Trim();
        mDoc.dbType = rdDbType.SelectedValue; //此出代码，如果重构要单独搞出去
        mDoc.tblTitle = arr_items[0];
        mDoc.tblName = arr_items[1];
        mDoc.tblDbName = txtPre.Text.Trim() + mDoc.tblName;
        mDoc.subFolder = arr_items.Length > 2 ? arr_items[2] : "test";
        mDoc.nameSpace = txtNameSpace.Text.Trim(); 
        
        //连续3行的字段解析
        row = arr_rows[1];
        mDoc.strTxts = row;
        string[] arr_fld_title = row.Split(',');
        row = arr_rows[2];
        mDoc.strNames = row;
        string[] arr_fld_name = row.Split(',');
        row = arr_rows[3];
        string[] arr_fld_dbtype = row.Split(',');
        mDoc.fieldCount = arr_fld_name.Length;
        if (arr_fld_dbtype.Length != mDoc.fieldCount || mDoc.fieldCount != arr_fld_title.Length)
        {
            mDoc.docMsg = string.Format("字段数不一致，请检查。{0}-{1}-{2}", arr_fld_title.Length, arr_fld_name.Length, arr_fld_dbtype.Length);
            int max_len = Math.Max(arr_fld_dbtype.Length, arr_fld_title.Length);
            max_len=Math.Max(max_len,arr_fld_name.Length);
            var sb=new StringBuilder();
            sb.Append("<table class=\"gridtable\"><tr><th>title</th><th>name</th><th>type</th></tr>");
            for (int i = 0; i < max_len; i++)
            {
                string red_star = "<font color='red'>*</font>";
                string name = red_star, title = red_star, dbtype = red_star;
                if (i < arr_fld_title.Length)
                {
                    title = arr_fld_title[i];
                }
                if (i < arr_fld_dbtype.Length) { dbtype = arr_fld_dbtype[i]; }
                if (i < arr_fld_name.Length) { name = arr_fld_name[i]; }
                sb.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>",
                    title, name, dbtype);
            }
            sb.Append("</table>");
            mDoc.v_table=sb.ToString();

            return mDoc;
        }
        mDoc.list.Clear();
        for (int i = 0; i < mDoc.fieldCount; i++)
        {
            var mod = new LIB.easyTableField();
            string fldTitle = arr_fld_title[i];
            mod.fieldName = arr_fld_name[i];
            //mod.fieldTitle = fldTitle;

            string len = arr_fld_dbtype[i].Substring(1, arr_fld_dbtype[i].Length - 1);
            mod.dbLength = len;
            string ty_alias = arr_fld_dbtype[i].Substring(0, 1);
            string dbType =mDoc.getDbTypeFromAlias(ty_alias);
            mod.dbType = dbType;
            string fieldType =mDoc.getFieldTypeFromAlias(ty_alias);
            mod.fieldType = fieldType;

            string LanguagefieldType = mDoc.getFieldLanguageTypeFromAlias(ty_alias);
            mod.LanguagefieldType = LanguagefieldType;

            mod.isMust = fldTitle.IndexOf("*") > 0; //需要验证
            mod.notInList = fldTitle.IndexOf("l") > 0; //列表不显示
            mod.needQuery = fldTitle.IndexOf("q") > 0; //列表里要查询
            mod.notInForm = fldTitle.IndexOf("0") > 0; //表单不提交

            mod.fieldTitle = fldTitle.Replace('*', ' ').Replace('l', ' ').Replace('q', ' ').Replace('0', ' ').TrimEnd();
            mDoc.list.Add(mod);
        }
        mDoc.docOk = true;
        return mDoc;
    }

   /// <summary>
    /// 生成单个表的sql语句
    /// </summary>
    /// <returns></returns>
    private string genSqlCode(LIB.easyDoc mDoc)
    {
        var strB = new StringBuilder();
        if (mDoc.dbType == "mysql")
        {
            string tblCreateType = rdTblCreateType.SelectedValue;
            if (tblCreateType == "2")
            {
                #region 代码拼接

                //strB.Append("--IF not EXISTS (SELECT 1 FROM sysobjects WHERE xtype='u' AND name='" + mDoc.tblName + "') \r\n\r\n");
                strB.Append("SET NAMES 'utf8';\r\n");
                strB.Append("-- 创建表[" + mDoc.tblTitle + "]开始: \r\n\r\n");
                //strB.Append(" -- alter table  `" + mDoc.tblName + "] add\r\n\r\n");
                strB.Append("-- DROP TABLE IF EXISTS `" + mDoc.tblName + "`;\r\n\r\n");
                strB.Append("CREATE TABLE `" + mDoc.tblDbName + "` (\r\n");
                strB.Append(" 	id bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',\r\n");
                string lines = "";
                foreach (var mod in mDoc.list)
                {
                    if (mod.fieldName == "id") continue;
                    if (mod.dbType == "int" && mod.dbLength == "4") mod.dbType = "smallint";
                    string line = " 	`" + mod.fieldName + "`" + mod.dbType;
                    switch (mod.dbType)
                    {
                        case "int":
                            line += "(" + (mod.dbLength == "" ? "11" : mod.dbLength) + ")";
                            break;
                        case "varchar":
                            line += "(" + mod.dbLength + ")";
                            break;
                        case "smallint":
                            line += "(" + mod.dbLength + ")";
                            break;
                        case "decimal":
                            line += "(18,2)";
                            break;
                            //case "datetime":
                            //    line += "datetime";
                            //    break;
                    }
                    line += " COMMENT '" + mod.fieldTitle + "'";
                    lines += line + ",";
                }
                //lines = lines.Substring(0, lines.Length - 1);
                lines = lines.Replace(",", ",\r\n");
                strB.Append(lines);
                strB.Append("    `status` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT '0' COMMENT '状态',\r\n");
                strB.Append("    `del_flag` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT '0' COMMENT '删除标识：0 存在  2  删除',\r\n");
                strB.Append("    `dept_id` bigint DEFAULT NULL COMMENT '部门主键',\r\n");
                strB.Append("    `create_by` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '创建人',\r\n");
                strB.Append("    `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',\r\n");
                strB.Append("    `update_by` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '更新人',\r\n");
                strB.Append("    `update_time` datetime CURRENT_TIMESTAMP On update CURRENT_TIMESTAMP NULL COMMENT '更新时间',\r\n");
                strB.Append("    `remark` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT '' COMMENT '备注',\r\n");
                strB.Append(" 	 PRIMARY KEY (`id`) USING BTREE\r\n");
                strB.Append(")ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC  COMMENT='" + mDoc.tblTitle + "';\r\n\r\n");

                strB.Append("-- 创建表[" + mDoc.tblTitle + "]结束。 \r\n\r\n");
                #endregion

            }
            else
            {
                #region 代码拼接

                //strB.Append("--IF not EXISTS (SELECT 1 FROM sysobjects WHERE xtype='u' AND name='" + mDoc.tblName + "') \r\n\r\n");
                strB.Append("SET NAMES 'utf8';\r\n");
                strB.Append("-- 创建表[" + mDoc.tblTitle + "]开始: \r\n\r\n");
                //strB.Append(" -- alter table  `" + mDoc.tblName + "] add\r\n\r\n");
                strB.Append("-- DROP TABLE IF EXISTS `" + mDoc.tblName + "`;\r\n\r\n");
                strB.Append("CREATE TABLE `" + mDoc.tblDbName + "` (\r\n");
                strB.Append(" 	id int(11) NOT NULL AUTO_INCREMENT,\r\n");
                string lines = "";
                foreach (var mod in mDoc.list)
                {
                    if (mod.fieldName == "id") continue;
                    if (mod.dbType == "int" && mod.dbLength == "4") mod.dbType = "smallint";
                    string line = " 	`" + mod.fieldName + "`" + mod.dbType;
                    switch (mod.dbType)
                    {
                        case "int":
                            line += "(" + (mod.dbLength == "" ? "11" : mod.dbLength) + ")";
                            break;
                        case "varchar":
                            line += "(" + mod.dbLength + ")";
                            break;
                        case "smallint":
                            line += "(" + mod.dbLength + ")";
                            break;
                        case "decimal":
                            line += "(18,2)";
                            break;
                            //case "datetime":
                            //    line += "datetime";
                            //    break;
                    }
                    line += " COMMENT '" + mod.fieldTitle + "'";
                    lines += line + ",";
                }
                //lines = lines.Substring(0, lines.Length - 1);
                lines = lines.Replace(",", ",\r\n");
                strB.Append(lines);
                strB.Append(" 	 PRIMARY KEY (`id`)\r\n");
                strB.Append(")ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8  COMMENT='" + mDoc.tblTitle + "';\r\n\r\n");

                strB.Append("-- 创建表[" + mDoc.tblTitle + "]结束。 \r\n\r\n");
                #endregion
            }
        }
        else if (mDoc.dbType == "orcale")
        {
            #region 代码拼接

            //strB.Append("--IF not EXISTS (SELECT 1 FROM sysobjects WHERE xtype='u' AND name='" + mDoc.tblName + "') \r\n\r\n");
            //strB.Append("begin\r\n");
            //strB.Append(" --------------------------\r\n");
            strB.Append(" -- 创建表[" + mDoc.tblTitle + "]开始: \r\n\r\n");
            strB.Append(" -- drop table  " + mDoc.tblName + " ;\r\n\r\n");
            strB.Append("   CREATE TABLE \"" + mDoc.tblName + "\" (\r\n");
            strB.Append(" 	 \"id\" Number(6) NOT NULL PRIMARY KEY ,\r\n");
            string lines = " ";
            foreach (var mod in mDoc.list)
            {
                if (mod.fieldName == "id") continue;
                if (mod.dbType == "datetime") mod.dbType = "date";
                if (mod.dbType == "decimal") mod.dbType = "number";
                if (mod.dbType == "int") mod.dbType = "number(6)";
                string line = " 	 \"" + mod.fieldName + "\" " + mod.dbType;
                switch (mod.dbType)
                {
                    case "varchar":
                        line += "(" + mod.dbLength + ")";
                        break;
                    case "number":
                        line += "(18,2)";
                        break;
                    //case "date":
                    //    line += "datetime";
                    //    break;
                }
                //if (mod.fieldName == "id") line += "IDENTITY (1, 1) PRIMARY KEY NOT NULL";
                lines += line + ",";
            }
            lines = lines.Substring(0, lines.Length - 1);
            lines = lines.Replace(",", ",\r\n");
            strB.Append(lines);
            //strB.Append(" 	 [recordDate] datetime default getdate()\r\n\r\n");
            strB.Append("\r\n   )\r\n");
            strB.Append("; \r\n");
            strB.Append("           CREATE SEQUENCE seq_" + mDoc.tblName + "\r\n");
            strB.Append("INCREMENT BY 1 -- 每次加几个\r\n");
            strB.Append(" START WITH 1 -- 从1开始计数\r\n");
            strB.Append("NOMAXVALUE -- 不设置最大值\r\n");
            strB.Append("NOCYCLE -- 一直累加，不循环\r\n");
            strB.Append("NOCACHE -- 不建缓冲区\r\n\r\n");
            strB.Append("; \r\n");


            strB.Append("CREATE OR REPLACE TRIGGER tri_" + mDoc.tblName + "  \r\n");
            strB.Append(" BEFORE INSERT ON \"" + mDoc.tblName + "\"  \r\n");
            strB.Append(" FOR EACH ROW  \r\n");
            strB.Append("  BEGIN  \r\n");
            strB.Append("    SELECT seq_" + mDoc.tblName + ".nextval INTO :new.\"id\"  FROM dual;  \r\n");
            strB.Append("  END;  \r\n");

            strB.Append("; \r\n");
            strB.Append(" -- 创建表[" + mDoc.tblTitle + "]结束。 \r\n");
            //strB.Append(" --------------------------\r\n\r\n");
            //strB.Append(" \r\n\r\n");
            //strB.Append(" end\r\n\r\n");

            #endregion

        }
        else
        {
            #region 代码拼接

            //strB.Append("--IF not EXISTS (SELECT 1 FROM sysobjects WHERE xtype='u' AND name='" + mDoc.tblName + "') \r\n\r\n");
            //strB.Append("begin\r\n");
            //strB.Append(" --------------------------\r\n");
            strB.Append(" -- 创建表[" + mDoc.tblTitle + "]开始: \r\n\r\n");
            //strB.Append(" -- alter table  [" + mDoc.tblName + "] add\r\n\r\n");
            strB.Append(" -- IF EXISTS (SELECT 1 FROM sysobjects WHERE xtype='u' AND name='" + mDoc.tblName + "') drop table " + mDoc.tblName + "\r\n");
            strB.Append("   CREATE TABLE [" + mDoc.tblName + "] (\r\n");
            strB.Append(" 	 [id] integer IDENTITY (1, 1) PRIMARY KEY NOT NULL ,\r\n");
            string lines = " ";
            foreach (var mod in mDoc.list)
            {
                if (mod.fieldName == "id") continue;
                string line = " 	 " + mod.fieldName + " " + mod.dbType;
                switch (mod.dbType)
                {
                    case "varchar":
                        line += "(" + mod.dbLength + ")";
                        break;
                    case "decimal":
                        line += "(18,2)";
                        break;
                        //case "date":
                        //    line += "datetime";
                        //    break;
                }
                //if (mod.fieldName == "id") line += "IDENTITY (1, 1) PRIMARY KEY NOT NULL";
                lines += line + ",";
            }
            lines = lines.Substring(0, lines.Length - 1);
            lines = lines.Replace(",", ",\r\n");
            strB.Append(lines);
            //strB.Append(" 	 [recordDate] datetime default getdate()\r\n\r\n");
            strB.Append("\r\n   )\r\n");
            strB.Append(" \r\n");
            strB.Append("  exec sp_addextendedproperty N'MS_Description',N'" + mDoc.tblTitle + " ',N'user',N'dbo',N'table',N'" + mDoc.tblName + "', NULL, NULL\r\n");
            foreach (var mod in mDoc.list)
            {
                strB.Append("  exec sp_addextendedproperty N'MS_Description',N'" + mod.fieldTitle + " ',N'user',N'dbo',N'table',N'" + mDoc.tblName + "',N'column',N'" + mod.fieldName + "'\r\n");
            }
            strB.Append(" \r\n");
            strB.Append(" -- 创建表[" + mDoc.tblTitle + "]结束。 \r\n");
            //strB.Append(" --------------------------\r\n\r\n");
            //strB.Append(" \r\n\r\n");
            //strB.Append(" end\r\n\r\n");
            #endregion
        }
        return strB.ToString();
    }

 
    /// <summary>
    /// 生成代码点击事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnTestGenrateModel_Click(object sender, EventArgs e)
    {
        BatDealDocModels();
        lblResult.Text = "";
        var sTemplates = LIB.trans.GetChecked(ckTemplates);
        //lblResult.Text = s;
        var arrTemplates= sTemplates.Split(',');
        //return;
        bool saveFile = true;
        string dir = iData.IO.GetCurrentPath() + "\\..\\output";
        if (saveFile && !System.IO.Directory.Exists(dir)) System.IO.Directory.CreateDirectory(dir);

        string currentFolder = rdTemplateFolders.SelectedValue;
        if (currentFolder == "") currentFolder = "default";

        for (int k = 0; k < arrTemplates.Length; k++)
        {
            var templateName = arrTemplates[k];
            if (templateName.Length <= 0)
            {
                continue;
            }
            else
            {
                templateName = currentFolder + "\\" + templateName;
                string ext = LIB.trans.getExt(templateName);
                for (int i = 0; i < listDoc.Count; i++)
                {
                    //if (i > 0) break;
                    var mod = listDoc[i];
                    string ret = genModelStr(mod,templateName);
                    //ret = ret.Replace("{strNames}", mod.strNames);
                    ret = ret.Replace("{date}", DateTime.Now.ToString());

                    string outFolderName = templateName.Replace("+", "\\");
                    string outFileName = "";
                    if (templateName.IndexOf("tblName") >= 0 || templateName.IndexOf("subFolder") >= 0)
                    {
                        outFolderName = outFolderName.Replace("[tblName]", mod.tblName).Replace("{tblName}", LIB.trans.upperFirstChar(mod.tblName));
                        outFolderName = outFolderName.Replace("{subFolder}", LIB.trans.upperFirstChar(mod.subFolder));
                        outFolderName = outFolderName.Replace("[subFolder]", mod.subFolder.ToLower());
                        outFileName = dir + "\\" + outFolderName;
                        int index = outFolderName.LastIndexOf("\\");
                        outFolderName = outFolderName.Substring(0, index);
                    }
                    else
                    {
                        //如果不包含tblName，则原文件名做文件夹，tblName做文件名
                        outFolderName = templateName.Replace(ext, "");
                        outFolderName = outFolderName.Replace("{subFolder}", LIB.trans.upperFirstChar(mod.subFolder));
                        outFolderName = outFolderName.Replace("[subFolder]", mod.subFolder);
                        outFileName = dir + "\\" + outFolderName + "\\" + mod.tblName + ext;
                    }
                     if (saveFile && !System.IO.Directory.Exists(dir + "\\" + outFolderName)) System.IO.Directory.CreateDirectory(dir + "\\" + outFolderName);
                    lblResult.Text += LIB.trans.codeInTextarea(ret,templateName,mod.tblName);
                    if (saveFile)
                    {
                        if (rdLanguage.SelectedValue == "php")
                        {
                            iData.IO.SaveFIleNoBOM(ret, outFileName);
                        }
                        else
                        {
                            iData.IO.SaveFIle(ret, outFileName);
                        }
                        
                    }
                }

            }

        }

    }
    /// <summary>
    /// 读取模板、替换变量并生成代码
    /// </summary>
    /// <param name="mDoc"></param>
    /// <param name="templateName"></param>
    /// <returns></returns>
    private string genModelStr(LIB.easyDoc mDoc,string templateName)
    {
        //string templateName = "\\templates\\"+;
        string cont = iData.IO.ReadTemplate("\\..\\templates\\" + templateName);
        string subFolderName = listDoc[0].subFolder;
        cont = cont.Replace("{subFolder}Controller", LIB.trans.upperFirstChar(subFolderName)+ "Controller");

        cont = cont.Replace("{subFolder}", LIB.trans.upperFirstChar(subFolderName));
        cont = cont.Replace("[subFolder]", subFolderName);
        if (cont.IndexOf("[folder start]") > 0)
        {
            return dealSubFolderStr(cont);
        }
        else
        {
            return dealTblCode(mDoc, cont);
        }
    }

    /// <summary>
    /// 对单表代码的处理
    /// </summary>
    /// <param name="mDoc"></param>
    /// <param name="cont"></param>
    /// <returns></returns>
    private string dealTblCode(LIB.easyDoc mDoc,string cont)
    {
        cont = cont.Replace("{strNames}", mDoc.strNames);
        cont = cont.Replace("[tblName]", mDoc.tblName).Replace("[tblTitle]", mDoc.tblTitle);
        cont = cont.Replace("[dbName]", mDoc.dbName).Replace("[nameSpace]", mDoc.nameSpace);
        cont = cont.Replace("{dbName}", LIB.trans.upperFirstChar(mDoc.dbName)).Replace("{dbName}", mDoc.nameSpace);
        cont = cont.Replace("\n", "");
        cont = cont.Replace("{tblName}", LIB.trans.upperFirstChar(mDoc.tblName));
        string[] arrLine = cont.Split('\r');
        var sb = new StringBuilder();
        bool loopStart = false;

        var sa = new StringBuilder();
        for (int i = 0; i < arrLine.Length; i++)
        {
            var strLine = arrLine[i];
            bool noCrlf = false;
            if (strLine.Contains("^"))
            {
                noCrlf = true;
                //strLine = strLine.Replace("^", "");
            }

            if (strLine.Trim() == "[loop start]")
            {
                loopStart = true;
                sa.Clear();
                continue;
            }
            if (!loopStart)
            {
                sb.Append(strLine);
                if (!noCrlf) sb.Append("\r\n");
            }
            else
            {
                if (strLine.Contains("[loop end]"))
                {
                    loopStart = false;
                    //循环部分结束并已读取到了sa里
                    //下面要对sa循环处理了。
                    var fldList = mDoc.list;
                    int index = 0;
                    foreach (var mField in fldList)
                    {
                        if (mField.fieldName == "id") continue; // id默认不显示

                        string fldCode =dealLoopText(mField,sa.ToString(),index);
                        if (fldCode != "")
                        {
                            sb.Append(fldCode);
                        }
                        if (!noCrlf) sb.Append("\r\n");
                        index++;
                    }
                    //sb.Append(sa + "\r");
                }
                else
                {
                    //循环开始，并没有结束
                    sa.Append(strLine);
                    if (!noCrlf) sa.Append("\r\n");
                    var temp = sa.ToString();
                    //var kk = 1;
                }
            }

        }
        return sb.ToString();
    }

    private string dealLoopText(easyTableField mField,string fldCode,int index=-1)
    {
        var sb = new StringBuilder();
        string codeType = "普通";
        //先对循环的内容类型进行判断
        if ((fldCode.Contains("tdFormLeft")&&fldCode.Contains("input"))||fldCode.Contains("<Run Text=\"\""))
        {
            codeType = "添加表单";
        }
        else if (fldCode.Contains("<label>[fldTitle]")||fldCode.Contains("QueryLabelStyle"))
        {
            codeType = "查询条件";
        }
        else if (fldCode.Contains("<th>[fldTitle]</th>")||fldCode.Contains("<td>[[info.[fldName]]]</td>"))
        {
            codeType = "列表";
        }
        else if (fldCode.Contains("sql.Where")||fldCode.Contains("strlen"))
        {
            codeType = "查询条件后台";
        }
        else if (fldCode.Contains("[fldDefaultValue]"))
        {
            codeType = "添加保存初始值";
        }
        else if (fldCode.Contains("LIB.Check")||fldCode.Contains("require")||fldCode.Contains("不能为空")||fldCode.Contains("if (!HasValue"))
        {
            codeType = "表单验证";
        }
        switch (codeType)
        {
            case "添加表单":
                if (fldCode.IndexOf("id=\"txt") > 0)
                {
                    if (mField.dbType.StartsWith("int") || mField.dbType.StartsWith("decimal"))
                    {
                        fldCode = fldCode.Replace("type=\"text\"", "type=\"number\"");
                    }
                    else if (mField.dbType.StartsWith("date") || mField.dbType.StartsWith("Date"))
                    {
                        fldCode = fldCode.Replace("type=\"text\"", "type=\"date\"");
                    }
                    if (mField.isMust)
                    {
                        fldCode = fldCode.Replace("<em> ", "<em> * ");
                        fldCode = fldCode.Replace("<Run Text=\"\"", "<Run Text=\"*\"");
                    }
                }
                if (mField.dbType.StartsWith("date") || mField.dbType.StartsWith("Date"))
                {
                    fldCode = fldCode.Replace("<TextBox Text", "<DatePicker  SelectedDate");
                }
                if (mField.isMust)
                {
                    fldCode = fldCode.Replace("<Run Text=\"\"", "<Run Text=\"*\"");
                }
                if (mField.notInForm) return "";
                break;
            case "添加保存初始值":
                if (mField.notInForm)
                {
                    var fldDefaultValue = "\"\"";
                    if (mField.dbType.StartsWith("int") || mField.dbType.StartsWith("decimal"))
                    {
                        fldDefaultValue="0";
                    }
                    else if (mField.dbType.StartsWith("date") || mField.dbType.StartsWith("Date"))
                    {
                        fldDefaultValue = "DateTime.Now";
                        if(rdLanguage.SelectedValue=="php") fldDefaultValue = "date(\"Y-m-d H:i:s\")";
                    }
                    fldCode = fldCode.Replace("[fldDefaultValue]", fldDefaultValue);
               }
                else
                {
                    return "";
                }
                break;
            case "查询条件":
                if (!mField.needQuery) return "";
                break;
            case "表单验证":
                if (!mField.isMust) return "";
                break;
            case "列表":
                if (mField.notInList) return "";
                break;
            case "查询条件后台":
                if (!mField.needQuery) return "";
                break;
            default:
                break;

        }
        fldCode = fldCode.Replace("[fldTitle]", mField.fieldTitle).Replace("[fldName]", mField.fieldName);
        fldCode = fldCode.Replace("[fldType]", mField.fieldType);
        fldCode = fldCode.Replace("[LfldType]", mField.LanguagefieldType);
        fldCode = fldCode.Replace("{fldName}", LIB.trans.upperFirstChar(mField.fieldName));
        if (index > -1)
        {
            fldCode = fldCode.Replace("[index]", index.ToString());
        }

        return fldCode;
    }

    /// <summary>
    /// 对于包含子文件夹的模板 处理
    /// </summary>
    /// <param name="cont"></param>
    /// <returns></returns>
    private string dealSubFolderStr(string cont)
    {
        //cont = cont.Replace("[tblName]", mDoc.tblName).Replace("[tblTitle]", mDoc.tblTitle);
        //cont = cont.Replace("[dbName]", mDoc.dbName).Replace("[nameSpace]", mDoc.nameSpace);
        //cont = cont.Replace("{dbName}", LIB.trans.upperFirstChar(mDoc.dbName)).Replace("{dbName}", mDoc.nameSpace);
        //cont = cont.Replace("\n", "");
        //cont = cont.Replace("{tblName}", LIB.trans.upperFirstChar(mDoc.tblName));
        cont = cont.Replace("\n", "");
        string[] arrLine = cont.Split('\r');
        
        var sb = new StringBuilder();
        bool loopStart = false;
        var subFolerName = "";
        var sa = new StringBuilder();
        for (int i = 0; i < arrLine.Length; i++)
        {
            var strLine = arrLine[i];
            bool noCrlf = false;
            if (strLine.Contains("^"))
            {
                noCrlf = true;
                //strLine = strLine.Replace("^", "");
            }

            if (strLine.Trim() == "[folder start]")
            {
                loopStart = true;
                sa.Clear();
                continue;
            }
            if (!loopStart)
            {
                sb.Append(strLine);
                if (!noCrlf) sb.Append("\r\n");
            }
            else
            {
                if (strLine.Trim() == "[folder end]")
                {
                    loopStart = false;
                    //循环部分结束并已读取到了sa里
                    //下面要对sa循环处理了。
                    for (int k = 0; k < listDoc.Count; k++)
                    {
                        //if (i > 0) break;
                        var mod = listDoc[k];
                        subFolerName = mod.subFolder;
                        string tbldCode =dealTblCode(mod,sa.ToString());
                        sb.Append(tbldCode);
                    }

                }
                else
                {
                    //循环开始，并没有结束
                    sa.Append(strLine);
                    if (!noCrlf) sa.Append("\r\n");
                    var temp = sa.ToString();
                    //var kk = 1;
                }
            }

        }
        return sb.ToString().Replace("{subFolder}", LIB.trans.upperFirstChar(subFolerName)).Replace("[subFolder]", subFolerName);
    }

    /// <summary>
    /// 模板文件夹点击切换事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void rdTemplateFolders_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindTemplateFiles();
    }
    protected void btnFormatCheck_Click(object sender, EventArgs e)
    {

    }
}